<template>
  <div class="body">
    <header class="header">
      <div class="title">
        <img src="../assets/images/01_11.png" alt="" class="img_zuo" @click="back" />
        <div>地图</div>
      </div>
    </header>
    <div class="main top" id="ditu"></div>
  </div>
</template>

<script>
  import qs from 'qs';
  export default {
    name: 'ShowMapPos',
    data() {
      return {
        map: null,
        userMarker:null
      }
    },
    mounted() {
      var _this = this;

    },

    //进入该页面时，用之前保存的滚动位置赋值
    methods: {
      //  返回
      back() {
        // this.$router.push("/dwxc_2_Pointcreation");
        this.$router.back()
      },
      createMap() {
        // 创建地图
        this.map = new AMap.Map('ditu', {
          resizeEnable: true,
          zoomEnable: true, //地图是否可缩放，默认值为true
        });
        // 设置中心点
        var position = new AMap.LngLat(_this.$global_msg.centerJwd.jd,_this.$global_msg.centerJwd.wd);  // 标准写法
        this.map.setCenter(position);
        // 设置地图级别 // PC上，参数zoom可设范围：[3,18]；// 移动端：参数zoom可设范围：[3,19]
        this.map.setZoom(16);
      },
      getJwdByDz(cx_obj){//根据地址查询经纬度
        if(!AMap){
          return;
        }
        var _this = this;
        AMap.plugin('AMap.Geocoder', function() {
          var geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            city: '全国'
          })

          geocoder.getLocation(cx_obj.address, function(status, result) {
            var obj = null;
            if (status === 'complete' && result.info === 'OK') {
              // result中对应详细地理坐标信息
              if(result.geocodes&&result.geocodes.length>0){
                //console.log(result.geocodes[0]);
                obj = result.geocodes[0].location;
              }
            }
            if(obj){
              _this.markUser(obj.lng,obj.lat,cx_obj.address);
            }else{
              _this.$toast('没有查询到');
            }
          })
        })
      },
      getDzByJwd(jd,wd){//根据经纬度查询地址
        if(!AMap){
          return;
        }
        var _this = this;
        AMap.service(["AMap.PlaceSearch"], function () {
          var placeSearch = new AMap.PlaceSearch({
            pageSize: 50,    // 每页10条
            pageIndex: 1,    // 获取第一页
            // city: city       // 指定城市名(如果你获取不到城市名称，这个参数也可以不传，注释掉)
          });
          // 第一个参数是关键字，这里传入的空表示不需要根据关键字过滤
          // 第二个参数是经纬度，数组类型
          // 第三个参数是半径，周边的范围
          // 第四个参数为回调函数
          placeSearch.searchNearBy('', [jd,wd], 1000, function (status, result) {
            console.log("status:", status)
            console.log("result:", result)
            if (result.info === 'OK') {
              var locationList = result.poiList.pois; // 周边地标建筑列表
              console.log(locationList)
              if(locationList&&locationList.length>0){
                _this.markUser(jd,wd,locationList[0].address);
              }else{
                _this.$toast('没有查询到');
              }
            } else {
              console.log('获取位置信息失败!');
            }
          });
        });
      },
      markUser(jd,wd,dz) {//用户标点
        // console.log(lnglat)
        var _this = this;
        var img_url = require('../assets/images/dwxc/dwpc_25.gif');
        var content = '';
        content+='<div style="text-align:center;margin-top:0.11044658064516133rem;margin-left: -0.1111rem;">';
        	content+='<img style="width: 0.6019rem;height:0.8154774193548386rem;" src="'+img_url+'"/>';
          content += '<div style="white-space: nowrap;position: absolute;bottom: -0.5rem;width: 1.851851rem;display: flex;justify-content: center;left: -0.777777rem;">' + dz + '</div>'
          //content+='<div style="position: absolute;bottom: 0;white-space: nowrap;font-size: 0.333333rem;top: 0.231481rem;left: 0.385rem;">'+dz+'</div>';
        content+='</div>';
        var user_marker = new AMap.Marker({
          position: [jd, wd],// 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          //title: '标点',
          content: content,
          zIndex: 110,
          zoom: 19,
          // anchor:'center', // 设置锚点方位
        });

        this.map.setCenter([jd, wd]);
        // 设置点标记的动画效果，此处为弹跳效果
        //marker.setAnimation('AMAP_ANIMATION_BOUNCE');
        // 将创建的点标记添加到已有的地图实例：
        //marker.dataObj = obj;
        _this.map.add(user_marker);
        _this.userMarker = user_marker;
        _this.map.setFitView();
      },
      init(){
        var _this = this;
        if(!_this.map){
          var AMap_timer = setInterval(function(){
            try{
              if(AMap){
                clearInterval(AMap_timer);
                _this.createMap();
              }
            }catch(e){
              //TODO handle the exception
            }
          },100);
        }
        var timer = setInterval(function(){
          if(_this.map){
            clearInterval(timer);
            _this.init2();
          }
        },100);
      },
      init2(){
        var _this = this;
        var ShowMapPosObj = localStorage.getItem("ShowMapPosObj")?JSON.parse(localStorage.getItem("ShowMapPosObj")):{};
        if(_this.userMarker){
          _this.map.remove(_this.userMarker);
        }
        _this.userMarker = null;
        var jwdObj = null;
        if(ShowMapPosObj.jwd&&ShowMapPosObj.jwd.length>0&&ShowMapPosObj.jwd.split(',').length==2){
          jwdObj = ShowMapPosObj.jwd.split(',');
        }
        if(ShowMapPosObj.jwd){
          if(ShowMapPosObj.address){
            _this.markUser(jwdObj[0],jwdObj[1],ShowMapPosObj.address);
          }else{
            _this.getDzByJwd(jwdObj[0],jwdObj[1]);
          }
        }else{
          if(ShowMapPosObj.address){
            _this.getJwdByDz(ShowMapPosObj)
          }else{
            _this.map.setZoom(16);
          }
        }
      }
    },
    //进入该页面时
    beforeRouteEnter (to, from, next) {
        next(vm => {
          vm.init();
        })
    },
    //离开该页面时
    beforeRouteLeave(to, from, next) {
        next()
    },
    created() {

    },
    mounted() {
      //使用方法
      /*localStorage.setItem("ShowMapPosObj",JSON.stringify({
        jwd:'',
        address:'鱼洞轻轨站'
      }));
      this.$router.push("/ShowMapPos");*/
    },

  }
</script>

<style scoped>
  /* 头部 */
  .header {
    height: 1.8519rem;
    background: #007aff;
    padding-top: 0.8333rem;
    box-sizing: border-box;
    width: 100%;
    z-index: 20;
    font-size: 0.388888rem;
    position: fixed;
    top: 0;
    left: 0;
  }

  .title {
    padding: 0 0.3704rem;
    display: flex;
    align-items: center;
    color: #fff;
  }

  .title>div {
    width: 100%;
    font-size: 0.4444rem;
    text-align: center;
  }

  .img_zuo {
    width: 0.2593rem;
    height: 0.463rem;
  }

  .img_jia {
    width: 0.4444rem;
    position: absolute;
    right: 0.3704rem;
  }

  /*  */
  .main {
    flex: 1;
    height: 100vh;
  }

  .list_addss {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 0;
    height: 6.9444rem;
    background: #fff;
    overflow-y: auto;
  }

  .list_addss_item {
    border-bottom: 1Px solid #ccc;
    height: 1.3889rem;
    box-sizing: border-box;
    overflow: hidden;
    word-break: keep-all;
    text-overflow: ellipsis;
    font-size: 0.3889rem;
    line-height: 1.3889rem;
    padding-left: 0.3704rem;
  }

  .active {
    background: #2D5DFD;
    color: #fff;
  }
</style>
